/**
 * 用户配置工具函数
 * 用于处理用户配置数据的缓存和转换
 */

import { getUserConfigPage } from "@/api/system/userConfig";

/**
 * 用户配置缓存前缀
 */
export const USER_CONFIG_CACHE_PREFIX = "user_config_";

/**
 * 用户配置键名映射
 */
export const USER_CONFIG_KEYS = {
  WORK_SHIFT: "workShift", // 班次
  WORK_CLASS: "workClass", // 班别
  PROCESS_NO: "processNo", // 工序编码
  PROCESS_NAME: "processName", // 工序名称
  PROD_CENTER_NO: "prodCenterNo", // 机组编码
  PROD_CENTER: "prodCenter", // 机组名称
  WAREHOUSE: "warehouse", // 仓库
};

/**
 * 从用户配置数据中提取工作信息
 * @param {Object} userConfig - 用户配置数据
 * @returns {Object} 工作信息对象
 */
export function extractWorkInfo(userConfig) {
  if (!userConfig || typeof userConfig !== "object") {
    return {};
  }

  return {
    workShift: userConfig[USER_CONFIG_KEYS.WORK_SHIFT] || "",
    workClass: userConfig[USER_CONFIG_KEYS.WORK_CLASS] || "",
    processNo: userConfig[USER_CONFIG_KEYS.PROCESS_NO] || "",
    processName: userConfig[USER_CONFIG_KEYS.PROCESS_NAME] || "",
    prodCenterNo: userConfig[USER_CONFIG_KEYS.PROD_CENTER_NO] || "",
    prodCenter: userConfig[USER_CONFIG_KEYS.PROD_CENTER] || "",
    warehouse: userConfig[USER_CONFIG_KEYS.WAREHOUSE] || "",
  };
}

/**
 * 将工作信息转换为配置对象格式
 * @param {Object} workInfo - 工作信息
 * @returns {Object} 配置对象
 */
export function transformWorkInfoToConfig(workInfo) {
  const config = {};

  if (workInfo.workShift)
    config[USER_CONFIG_KEYS.WORK_SHIFT] = workInfo.workShift;
  if (workInfo.workClass)
    config[USER_CONFIG_KEYS.WORK_CLASS] = workInfo.workClass;
  if (workInfo.process) config[USER_CONFIG_KEYS.PROCESS] = workInfo.process;
  if (workInfo.processName)
    config[USER_CONFIG_KEYS.PROCESS_NAME] = workInfo.processName;
  if (workInfo.prodLine) config[USER_CONFIG_KEYS.PROD_LINE] = workInfo.prodLine;
  if (workInfo.prodCenter)
    config[USER_CONFIG_KEYS.PROD_CENTER] = workInfo.prodCenter;
  if (workInfo.warehouse)
    config[USER_CONFIG_KEYS.WAREHOUSE] = workInfo.warehouse;

  return config;
}

/**
 * 获取用户配置数据（带缓存）
 * @param {number} userId - 用户ID
 * @param {boolean} forceRefresh - 是否强制刷新缓存
 * @returns {Promise<Object>} 用户配置数据
 */
export async function getUserConfigWithCache(userId, forceRefresh = false) {
  if (!userId) {
    throw new Error("用户ID不能为空");
  }

  const cacheKey = `${USER_CONFIG_CACHE_PREFIX}${userId}`;
  const cachedData = uni.getStorageSync(cacheKey);

  if (cachedData && !forceRefresh && !isUserConfigCacheExpired(userId)) {
    // 确保缓存数据完整，用于后续updateConfig使用
    // id是配置主键，userid是用户ID，两个字段都需要保留
    return cachedData;
  }
  const configData = {
    pageNum: 1,
    pageSize: 1,
    userId: userId,
  };

  const res = await getUserConfigPage(configData);

  if (res.code === 0) {
    // 直接使用API返回的原始数据，保持id和userid字段完整
    const configData = res.data.list[0] || {};

    // 调试日志：检查返回的数据结构
    console.log("getUserConfig API返回数据:", configData);
    console.log("配置数据中id字段:", configData.id);
    console.log("配置数据中userid字段:", configData.userid);

    uni.setStorageSync(cacheKey, configData);
    uni.setStorageSync(`${cacheKey}_timestamp`, Date.now());
    return configData;
  } else {
    throw new Error(res.msg || "获取用户配置失败");
  }
}

/**
 * 清除用户配置缓存
 * @param {number} userId - 用户ID
 */
export function clearUserConfigCache(userId) {
  const cacheKey = `user_config_${userId}`;
  uni.removeStorageSync(cacheKey);
  uni.removeStorageSync(`${cacheKey}_timestamp`);
}

/**
 * 检查缓存是否过期
 * @param {number} userId - 用户ID
 * @param {number} maxAge - 最大有效期（毫秒），默认1小时
 * @returns {boolean} 是否过期
 */
export function isUserConfigCacheExpired(
  userId,
  maxAge = 2 * 24 * 60 * 60 * 1000
) {
  // 默认2天
  const cacheKey = `user_config_${userId}_timestamp`;
  const timestamp = uni.getStorageSync(cacheKey);

  if (!timestamp) return true;

  return Date.now() - timestamp > maxAge;
}

export default {
  USER_CONFIG_CACHE_PREFIX,
  USER_CONFIG_KEYS,
  extractWorkInfo,
  transformWorkInfoToConfig,
  getUserConfigWithCache,
  clearUserConfigCache,
  isUserConfigCacheExpired,
};
